package fr.univ.surveyonline.question.xmlbuilder;

import java.util.Iterator;

import fr.univ.surveyonline.datastore.DatastoreKeyResponse;
import fr.univ.surveyonline.question.*;

public class transformKey {
	
	public static FormField transform_key(FormField f) {
		FormField res = new FormField();
		Iterator<ICompositeField> it = f.getIterator();
		while (it.hasNext()) {
			ICompositeField cf = it.next();
			ICompositeField resComposite;
			if (cf.getClass() == BooleanField.class) {
				resComposite = new BooleanField();
			} else if (cf.getClass() == DropDownChoiceField.class) {
				resComposite = new DropDownChoiceField();
			}  else if (cf.getClass() == RadioButtonChoiceField.class) {
				resComposite = new RadioButtonChoiceField();
			}  else if (cf.getClass() == CheckBoxChoiceField.class) {
				resComposite = new CheckBoxChoiceField();
			} else if (cf.getClass() == TextField.class) {
				resComposite = new TextField();
			} else {
				throw new IllegalStateException("Format non pris en compte");
			}
			
			resComposite.setQuestion(cf.getQuestion());
			resComposite.setDescription(cf.getDescription());
			resComposite.setname(cf.getname());
			
			if (cf.getType() != TypeCompositeField.TEXT_FIELD) {
				IChoiceField icf = (IChoiceField) cf;
				transform_key_answers(icf,(IChoiceField) resComposite);
			}
			res.addComposite(resComposite);
		}
		
		return res;
	}

	private static void transform_key_answers(IChoiceField icf,IChoiceField copy) {
		if (icf.getType() == TypeCompositeField.MULTIPLE_SUCCESSOR_FIELD) {
			IMultipleSuccessorField msf = (IMultipleSuccessorField) icf;
			IMultipleSuccessorField copy2 = (IMultipleSuccessorField) copy;
			
			for (DatastoreKeyResponse key : msf.getAllKey()) {
				DatastoreKeyResponse newKey =  copy.addAnswer(icf.getAnswer(key));
				if (msf.getChildren(key) != null) {
					copy2.setChildren(transform_key(msf.getChildren(key)), newKey);
				}
			}			
		} else {
			for (DatastoreKeyResponse key : icf.getAllKey()) {
				copy.addAnswer(icf.getAnswer(key));
			}
		}
	}
}
